<template>
    <div class="container">
      <TManageSidebar />
      <div class="right-content">
        <main class="main">
          <div class="statistics">
            <div class="statistic-item">
              <span>总学生人数: {{ studentCount }}</span>
            </div>
            <div class="statistic-item">
              <span>总作业份数: {{ assignmentCount }}</span>
            </div>
            <div class="statistic-item">
              <span>总出勤率: {{ attendanceRate }}%</span>
            </div>
          </div>

          <div class="course-select-container">
            <el-select
              v-model="selectedCourse"
              placeholder="请选择课程"
              class="course-select"
              @change="handleCourseChange"
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="course in courseList"
                :key="course.courseManageId"
                :label="formatCourseLabel(course)"
                :value="course.courseManageId"
              />
            </el-select>
          </div>

          <div class="charts">
            <div class="chart-container">
              <h2>上课出勤率统计</h2>
              <v-chart :option="attendanceChartOption" autoresize />
            </div>
            <div class="chart-container">
              <h2>作业数据统计</h2>
              <v-chart :option="assignmentChartOption" autoresize />
            </div>
          </div>
        </main>
      </div>
    </div>
  </template>
  
  <script setup>
  import TManageSidebar from '@/components/TManageSidebar.vue';
  import { ref, onMounted, computed } from 'vue';
  import VChart from 'vue-echarts';
  import { use } from 'echarts/core';
  import { LineChart } from 'echarts/charts';
  import {
    TitleComponent,
    TooltipComponent,
    GridComponent,
    LegendComponent,
    DataZoomComponent
  } from 'echarts/components';
  import { CanvasRenderer } from 'echarts/renderers';
  import { ElMessage } from 'element-plus';
  import { useRoute } from 'vue-router';
  import { getAttendanceStatistics, getAssignmentStatistics } from '@/api/statistics';
  import { courseManageListService } from '@/api/course';

  // 注册必须的组件
  use([
    CanvasRenderer,
    LineChart,
    TitleComponent,
    TooltipComponent,
    GridComponent,
    LegendComponent,
    DataZoomComponent
  ]);

  // 初始化数据变量
  const attendanceRates = ref([0.95, 0.92, 0.88, 0.96, 0.93, 0.91, 0.89, 0.94, 0.97, 0.90]);
  const absentRates = ref([0.05, 0.08, 0.12, 0.04, 0.07, 0.09, 0.11, 0.06, 0.03, 0.10]);
  const submitRates = ref([0.85, 0.88, 0.92, 0.90, 0.95, 0.87, 0.89, 0.93, 0.91, 0.94]);
  const averageScores = ref([0.75, 0.82, 0.79, 0.85, 0.88, 0.77, 0.81, 0.83, 0.80, 0.86]);

  // 模拟数据统计
  const studentCount = ref(99);
  const assignmentCount = ref(2);
  const interactionCount = ref(8);
  const attendanceRate = ref(100);

  // 模拟更多的数据点
  const lectureData = ref([
    '第一讲', '第二讲', '第三讲', '第四讲', '第五讲', 
    '第六讲', '第七讲', '第八讲', '第九讲', '第十讲'
  ]);

  // 课程相关数据
  const courseList = ref([]);
  const selectedCourse = ref('');

  // 获取课程列表
  const fetchCourseList = async () => {
    try {
      const response = await courseManageListService();
      if (response.code === 0 && response.data) {
        courseList.value = response.data;
        if (courseList.value.length > 0) {
          selectedCourse.value = courseList.value[0].courseManageId;
          await fetchData(selectedCourse.value);
        }
      } else {
        ElMessage.error('获取课程列表失败');
      }
    } catch (error) {
      console.error('获取课程列表失败:', error);
      ElMessage.error('获取课程列表失败，请稍后重试');
    }
  };

  // 处理课程选择变化
  const handleCourseChange = async (courseManageId) => {
    selectedCourse.value = courseManageId;
    await fetchData(courseManageId);
  };

  // 获取统计数据
  const fetchData = async (courseManageId) => {
    try {
      const attendanceRes = await getAttendanceStatistics({ courseManageId: courseManageId });
      if (attendanceRes.code === 0) {
        lectureData.value = attendanceRes.data.lectures;
        attendanceRates.value = attendanceRes.data.attendanceRates;
        absentRates.value = attendanceRes.data.absentRates;
      }

      const assignmentRes = await getAssignmentStatistics({ courseManageId: courseManageId });
      if (assignmentRes.code === 0) {
        submitRates.value = assignmentRes.data.submitRates;
        averageScores.value = assignmentRes.data.averageScores;
      }
    } catch (error) {
      console.error('获取数据失败:', error);
    }
  };

  // 计算当前显示的数据范围
  const getVisibleData = (allData, start, end) => {
    const startIndex = Math.floor(start * allData.length);
    const endIndex = Math.ceil(end * allData.length);
    return allData.slice(startIndex, endIndex);
  };

  const createChartOption = (title, data, rates1, rates2, series1Name, series2Name) => {
    const showSlider = data.length > 5;
    
    return {
      title: {
        text: title,
        left: 'center',
        top: 0
      },
      tooltip: {
        trigger: 'axis',
        formatter: function (params) {
          let result = params[0].axisValueLabel + '<br/>';
          params.forEach(param => {
            result += param.seriesName + ': ' + 
              (param.value * 100).toFixed(1) + '%<br/>';  // tooltip也显示百分比
          });
          return result;
        }
      },
      legend: {
        data: [series1Name, series2Name],
        top: 30
      },
      grid: {
        top: 80,
        left: 50,
        right: 50,
        bottom: showSlider ? 80 : 50,
        containLabel: true
      },
      dataZoom: [{
        type: 'slider',
        show: showSlider,
        xAxisIndex: 0,
        start: 0,
        end: showSlider ? (5 / data.length) * 100 : 100,
        bottom: 20,
        height: 30,
        borderColor: 'transparent',
        backgroundColor: '#f5f7fa',
        fillerColor: 'rgba(64, 158, 255, 0.2)',
        handleStyle: {
          color: '#409EFF'
        },
        showDetail: true,
        moveOnMouseMove: false,
        minSpan: (1 / data.length) * 100,  // 最小可以显示1个数据点
        maxSpan: 100  // 最大可以显示所有数据点
      }],
      xAxis: {
        type: 'category',
        data: data,
        axisLabel: {
          rotate: 45,
          interval: 0,
          margin: 8
        },
        axisTick: {
          alignWithLabel: true
        }
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 1,
        interval: 0.1,
        axisLabel: {
          formatter: (value) => {
            return (value * 100).toFixed(0) + '%';  // 将小数转换为百分比
          }
        }
      },
      series: [
        {
          name: series1Name,
          type: 'line',
          data: rates1,
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          lineStyle: { width: 2 }
        },
        {
          name: series2Name,
          type: 'line',
          data: rates2,
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          lineStyle: { width: 2 }
        }
      ]
    };
  };

  // 出勤率图表配置
  const attendanceChartOption = computed(() => 
    createChartOption(
      '上课出勤率统计',
      lectureData.value,
      attendanceRates.value,
      absentRates.value,
      '出勤率',
      '缺勤率'
    )
  );

  // 作业数据图表配置
  const assignmentChartOption = computed(() => 
    createChartOption(
      '作业完成情况统计',
      lectureData.value,
      submitRates.value,
      averageScores.value,
      '提交率',
      '平均分'
    )
  );

  // 格式化课程标签
  const formatCourseLabel = (course) => {
    if (!course) return '';
    return course.className 
      ? `${course.courseName} - ${course.className}`
      : course.courseName;
  };

  // 在组件挂载时获取课程列表和数据
  onMounted(() => {
    fetchCourseList();
  });
  </script>
  
  <style scoped>
  .container {
    display: flex;
    min-height: 100vh;
  }
  
  .right-content {
    margin-left: 160px; /* 与侧边栏宽度相同 */
    flex: 1;
  }

  .statistics {
    margin: 20px;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
    display: flex;
    justify-content: space-around;
  }

  .statistic-item {
    text-align: center;
    padding: 20px;
  }

  .statistic-item span {
    font-size: 20px;
    color: #303133;
  }

  .charts {
    margin: 20px;  /* 保持一致的外边距 */
    display: flex;
    flex-direction: row;
    gap: 20px;
  }

  .chart-container {
    flex: 1;  /* 让两个图表均分空间 */
    height: 400px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
    padding: 20px;
    min-width: 0;  /* 防止flex子项溢出 */
  }

  h2 {
    margin-top: 20px;
  }

  :deep(.echarts) {
    width: 100% !important;
    height: 100% !important;
  }

  .course-select-container {
    margin: 20px;  /* 与statistics相同的外边距 */
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  }

  .course-select {
    width: 100%; /* 设置下拉框宽度为100% */
  }

  :deep(.el-select-dropdown) {
    max-width: none !important;
  }

  :deep(.el-select-dropdown__item) {
    padding: 0 20px;
    white-space: nowrap;
  }
  </style>